package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomExceotion;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService{
    @Autowired
private SetmealDishService setmealDishService;

    @Override
    public boolean add(SetmealDto setmealDto) {
        //将数据添加到套餐表
        super.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            //给每个菜品添加setmeal的id
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //将套餐包含的菜品添加到套餐菜品表
        setmealDishService.saveBatch(setmealDishes);
        return true;
    }

    @Override
    public void deleteByIds(Long[] ids) {
        //查看批量删除的套餐中有没有正在起售的
        LambdaQueryWrapper<Setmeal> lam = new LambdaQueryWrapper<>();
        lam.eq(Setmeal::getStatus,1);
        lam.in(Setmeal::getId,ids);
        int count = super.count(lam);
        //如果有则提示不能删除
        if (count>0){
            throw new CustomExceotion("有正在售卖的套餐,不能删除!");
        }
        for (Long id : ids) {
            //删除套餐的菜品
            LambdaQueryWrapper<SetmealDish> lam2 = new LambdaQueryWrapper<>();
            lam2.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(lam2);
            //删除套餐
            super.removeById(id);
        }
    }
}
